package com.example.app.manager.c2;

import android.app.Activity;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Rect;
import android.graphics.SurfaceTexture;
import android.hardware.camera2.CameraCharacteristics;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.RequiresApi;
import android.text.TextUtils;
import android.util.Size;
import android.view.MotionEvent;
import android.view.Surface;

import com.example.app.manager.MediaRecorderManager;
import com.example.app.manager.OnCameraTakePictureBack;
import com.example.app.view.c2.PreviewC2View;

import java.io.File;

/**
 * 相机管理 5.0  系统用
 * 1.openBackgroundThread
 * 2.setTextureView
 * 3.initCamera2
 * Created by 郭敏 on 2018/3/21 0021.
 */
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public class Camera2Manager extends Camera2Base {
    private String tag = "Camera2Manager";
    private static Camera2Manager manager;
    //拍照
    private PreviewC2View textureView;
    private int textureViewWidth, textureViewHeight;

    public static Camera2Manager getInstance() {
        if (manager == null) {
            manager = new Camera2Manager();
        }
        return manager;
    }

    //开启线程
    public void openBackgroundThread() {
        onOpenThread();
    }

    //设置PreviewView
    public void setTextureView(PreviewC2View textureView) {
        this.textureView = textureView;
        this.textureViewWidth = textureView.getWidth();
        this.textureViewHeight = textureView.getHeight();
    }

    //获取预览控件的宽和高
    @Override
    protected int[] getPreviewWH() {
        return new int[]{textureViewWidth, textureViewHeight};
    }

    //获取Surface
    @Override
    protected Surface getPreviewSurface(Size previewSize) {
        SurfaceTexture texture = textureView.getSurfaceTexture();
        texture.setDefaultBufferSize(previewSize.getWidth(), previewSize.getHeight());
        Surface surface = new Surface(texture);
        return surface;
    }

    //初始化相机
    public void initCamera2(Context context) {
        isPictureProceed = false;
        initCamera(context);
        Size previewSize = getPreviewSize();
        //只能获取：1 竖屏 2 横屏
        int orientation = context.getResources().getConfiguration().orientation;
        if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
            //横屏
            textureView.setAspectRatio(
                    previewSize.getWidth(), previewSize.getHeight());
        } else {
            //竖屏
            textureView.setAspectRatio(
                    previewSize.getHeight(), previewSize.getWidth());
        }
        textureView.configureTransform(textureViewWidth, textureViewHeight, previewSize);
    }

    //关闭相机 ，关闭线程
    public void onDestroy() {
        onCloseThread();
        onCameraClose();
    }

    //设置相机缩放
    public void setCameraZoom(MotionEvent event) {
        if (isPictureProceed) {
            return;
        }
        if (!isOpne()) {
            return;
        }
        onCameraZoom(event);
    }

    //设置相机聚焦
    public void setCameraFocus(Rect rect) {
        if (isPictureProceed) {
            return;
        }
        if (!isOpne()) {
            return;
        }
        onCameraFocus(rect);
    }

    //获取相机数量
    public int getCameraAmount() {
        return getCameraCount();
    }

    //设置开启相机灯光
    public void setCameraLight() {
        if (!isOpne()) {
            return;
        }
        isPictureProceed = false;
        onCameraSwithLight();
    }

    //切换相机镜头
    public void setCameraSwitc() {
        isPictureProceed = false;
        onCameraSwitch();
    }

    //关闭相机
    public void setCameraClose() {
        onCameraClose();
    }

    //重新预览
    public void setRecoverPreview(Context context) {
        isPictureProceed = false;
        setResetPreview(context);
    }

    //开始录制视频
    public void onVideoStart(Activity activity, String videoPath) {
        onVideoStart(activity, videoPath, -1);
    }

    public void onVideoStart(Activity activity, String videoPath, int endTime) {
        if (!isOpne()) {
            return;
        }
        //设置录制时间 s
        creatorFile(videoPath);
        MediaRecorderManager.getInstance().setRecordTotalTime(endTime);
        onRecorderStart(activity, videoPath);
    }

    // 停止录制
    public void onVideoStop() {
        //关闭录制
        MediaRecorderManager.getInstance().setMediaWork(4);
        //关闭相机
        setCameraClose();
    }

    //true 拍照进行
    private boolean isPictureProceed;

    // 拍照
    public void onCameraTakePicture(String imagePath) {
        if (!isOpne()) {
            return;
        }
        if (!textureView.isAvailable()) {
            return;
        }
        isPictureProceed = true;
        creatorFile(imagePath);
        onTakePicture(imagePath);
    }


    //获取灯光开启状态
    public boolean isCameraLight() {
        return isLight();
    }

    public CameraCharacteristics getCameraParameter() {
        return getCameraCharacter();
    }


    //创建文件夹
    protected void creatorFile(String path) {
        if (TextUtils.isEmpty(path)) {
            return;
        }
        File file = new File(path);
        String p = file.getParent();
        File fileParent = new File(p);
        if (!fileParent.exists()) {
            boolean isOk = fileParent.mkdirs();
            d("创建文件夹" + isOk);
        }
    }

    //获取相机类型
    public int getCameraType() {
        CameraCharacteristics characteristics = getCameraParameter();
        if (characteristics == null) {
            return 0;
        }
        int lensFacing = characteristics.get(CameraCharacteristics.LENS_FACING);
        int j = 0;
        switch (lensFacing) {
            case CameraCharacteristics.LENS_FACING_FRONT:
                // 前置摄像头
                j = 1;
                break;
            case CameraCharacteristics.LENS_FACING_BACK:
                // 前置摄像头
                j = 2;
                break;
            case CameraCharacteristics.LENS_FACING_EXTERNAL:
                // 外置摄像头
                j = 3;
                break;
            default:
                j = 4;
                break;
        }
        return j;
    }

    //1：预览 20：拍照写入成功 21：拍照写入失败 31:录制视频错误
    @Override
    protected void onHandleMessage(Message msg) {
        Message m = new Message();
        m.what = msg.what;
        m.obj = msg.obj;
        m.arg1 = msg.arg1;
        m.arg2 = msg.arg2;
        mainHandler.sendMessage(m);
    }

    private void onTakePictureBack(String path, boolean isSucceed) {
        if (onCameraTakePictureBack == null) {
            return;
        }
        onCameraTakePictureBack.OnTakePictureBack(path, isSucceed);
    }

    //设置监听
    private OnCameraTakePictureBack onCameraTakePictureBack;

    private void setOnCameraTakePictureBack(OnCameraTakePictureBack onCameraTakePictureBack) {
        this.onCameraTakePictureBack = onCameraTakePictureBack;
    }

    private MainHandler mainHandler = new MainHandler();

    class MainHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Object obj = msg.obj;
            switch (msg.what) {
                case 20:
                    String p = "";
                    if (obj != null && obj instanceof String) {
                        p = (String) obj;
                    }
                    onTakePictureBack(p, true);
                    break;
                case 21:
                    p = "";
                    if (obj != null && obj instanceof String) {
                        p = (String) obj;
                    }
                    onTakePictureBack(p, false);
                    break;
            }
        }
    }
}
